package com.ylr.unittest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @ClassName NetworkUtils
 * @Description 网络工具
 **/
public class NetworkUtils {

    private static final Logger logger = LoggerFactory.getLogger(NetworkUtils.class);

    /**
     * 判断是否为json字符串
     * @return ipAddress
     */
    public static String getIpAddress() {
            Enumeration<NetworkInterface> nis;
            String ip = null;
            try {
                nis = NetworkInterface.getNetworkInterfaces();
                for (; nis.hasMoreElements();) {
                    NetworkInterface ni = nis.nextElement();
                    Enumeration<InetAddress> ias = ni.getInetAddresses();
                    for (; ias.hasMoreElements();) {
                        InetAddress ia = ias.nextElement();
                        //ia instanceof Inet6Address && !ia.equals("")
                        if (ia instanceof Inet4Address && !ia.getHostAddress().equals("127.0.0.1")) {
                            ip = ia.getHostAddress();
                        }
                    }
                }
            } catch (SocketException e) {
                logger.error("IP地址获取失败:", e);
            }
            logger.info("IP地址获取:", ip);
            return ip;
    }

}